#ifndef __COWSTRING_HPP__
#define __COWSTRING_HPP__

#include <stdio.h>
#include <iostream>

using std::ostream;

class CowString{
public:
    class charPoxy{
    public:
        charPoxy(CowString & rhs, ssize_t idx);
        ~charPoxy();
        //重载<<, =运算符
        friend ostream & operator<<(ostream & os, const charPoxy & rhs);
        char & operator=(const char ch);
    private:
        CowString & _self;
        int _idx;
    };
    friend ostream & operator<<(ostream & os, const charPoxy & rhs);

    CowString();//无参构造
    CowString(const char * pstr);//C风格字符串构造
    CowString(const CowString & rhs);//拷贝构造
    CowString & operator=(const CowString & rhs);//赋值运算符str2=str1
    charPoxy operator[](ssize_t idx);//下标访问运算符
    friend ostream & operator<<(ostream & os, const CowString & rhs);//输出流运算符
    ~CowString();//析构函数

    const char * c_str() const;//转为C风格字符串
    size_t size() const;//获取字符串长度
    void initRefConut();
    size_t useCount();
    void increasekRefCount();//引用计数+1
    void decreasekRefCount();//引用计数-1
private:
    char * malloc(const char * pstr = nullptr);
    static const int kRefCountLength = 4;
    char * _pstr;
};

ostream & operator<<(ostream & os, const CowString & rhs);

#endif